//
//  UserDao.m
//  parent
//
//  Created by 闫珍 on 15/5/20.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "UserDao.h"


static UserDao *user_dao;
static UserInfo *user_info;
static NSString *table_name = @"nbg_home_my_info";

@implementation UserDao
+(UserDao*)getInstance
{
    if(user_dao==nil){
        user_dao = [[UserDao alloc]init];
    }
    return user_dao;
}

-(UserInfo*)getUserInfo
{
    if(user_info ==nil ){
        user_info = [[UserInfo alloc] init];
    }
    
    if(user_info.hasLogin ==0 && user_info.userId == 0){
        [self loadInfo];
    }
    
    return user_info;
}

-(void)loadInfo
{
    NSArray *users = [[DBManager getInstanse]selectFrom:table_name items:@[@"id", @"nickname", @"hasLogin" , @"utype" , @"username" , @"phone" ,  @"avatar" , @"status" , @"access_token" , @"token_exp_time" , @"refresh_token" , @"fid" , @"frole",@"fcode" ] limits:@" hasLogin = 1 "];
    
    if(users.count>0){
        NSArray *user = [users objectAtIndex:0];
        user_info.userId = [[user objectAtIndex:0] integerValue];
        user_info.nickName = [user objectAtIndex:1];
        user_info.hasLogin =[[user objectAtIndex:2] integerValue];
        user_info.utype =[[user objectAtIndex:3] integerValue];
        user_info.userName = [user objectAtIndex:4];
        user_info.phone = [user objectAtIndex:5];
        user_info.avatar = [user objectAtIndex:6];
        user_info.status = [[user objectAtIndex:7]integerValue];
        user_info.access_token = [user objectAtIndex:8];
        user_info.token_exp_time = [[user objectAtIndex:9]integerValue];
        user_info.refresh_token = [user objectAtIndex:10];
        user_info.fid = [[user objectAtIndex:11]integerValue];
        user_info.frole = [[user objectAtIndex:12]integerValue];
        user_info.fcode = [user objectAtIndex:13];
    }

}

-(NSUInteger)getUserId
{
    return [self getUserInfo].userId;
}

-(NSUInteger)hasLogin
{
    return [self getUserInfo].hasLogin;
}

-(NSString *)getAccessToken
{
    return [self getUserInfo].access_token;
}

-(NSUInteger)getTokenExpTime
{
    return [self getUserInfo].token_exp_time;
}

-(BOOL)saveUserData:(NSDictionary*)dict
{
    if(dict ==nil){
        debugLog(@"数据为空");
        return NO;
    }else{
        NSUInteger uid = [[dict objectForKey:@"pid"]integerValue];
        if(uid>0){
            NSString *username = [dict objectForKey:@"username"];
            NSString *phone = [dict objectForKey:@"phone"];
            if(phone ==nil || [phone isEqualToString:@""]){
                phone = username;
            }
            NSString *name = [dict objectForKey:@"name"];
            NSUInteger fid = [[dict objectForKey:@"fid"]integerValue];
            NSUInteger frole = [[dict objectForKey:@"frole"]integerValue];
            NSString *avatar = [dict objectForKey:@"avatar"];
            NSUInteger utype = [[dict objectForKey:@"utype"]integerValue];
            NSString *access_token = [dict objectForKey:@"access_token"];
            NSUInteger token_exp_time = [[dict objectForKey:@"token_exp_time"]integerValue];
            NSString *refresh_token = [dict objectForKey:@"refresh_token"];
            NSUInteger status = [[dict objectForKey:@"status"]integerValue];
            NSString *fcode = [dict objectForKey:@"fcode"];
            if(fcode == nil ||fcode ==[NSNull null]){
                fcode = @"";
            }
            
            NSArray *users = [[DBManager getInstanse]selectFrom:table_name items:@[@"id" ] limits:[NSString stringWithFormat:@" id =%ld ",uid]];
            NSDictionary *dict = @{@"nickname":name,
                                   @"hasLogin":@(1),
                                   @"utype":@(utype),
                                   @"username":username,
                                   @"phone":phone,
                                   @"avatar":avatar,
                                   @"status":@(status),
                                   @"access_token":access_token,
                                   @"token_exp_time":@(token_exp_time),
                                   @"refresh_token":refresh_token,
                                   @"fid":@(fid),
                                   @"frole":@(frole),
                                   @"fcode":fcode
                                   };
            if(users.count>0){
                //更新数据
                
                BOOL result = [[DBManager getInstanse]updateTable:table_name updateDict:dict limits:[NSString stringWithFormat:@" id =%ld ",uid]];
                if(result) {
                    debugLog(@"更新用户信息成功~");
                }else{
                    debugLog(@"更新用户信息失败~");
                }
            }else{
                //插入数据
                NSMutableDictionary *insertDic =[[NSMutableDictionary alloc]initWithDictionary:dict];
                [insertDic setObject:@(uid) forKey:@"id"];
                BOOL result = [[DBManager getInstanse]insertTo:table_name dictionary:insertDic];
                if(result) {
                    debugLog(@"插入用户信息成功~");
                }else{
                    debugLog(@"插入用户信息失败~");
                }

            }
            [[DBManager getInstanse]updateTable:table_name updateDict:@{@"hasLogin":@(0)} limits:[NSString stringWithFormat:@" id != %ld ",uid]];

        }
    }
    return YES;
}

//更新用户信息，比如昵称、头像等
//reload表示更改完数据之后是否立即更新user_info模型
-(BOOL)updateUserInfo:(NSDictionary *)dict withReload:(BOOL)reload
{
    BOOL result = [[DBManager getInstanse]updateTable:table_name updateDict:dict limits:[NSString stringWithFormat:@" id =%ld ",[self getUserInfo].userId]];
    if(result){
        if(reload){
            [self loadInfo];
        }
    }
    return result;
}

-(NSArray*)getMyBabies
{
    NSLog(@"self.fID: %ld", (long)[self getUserInfo].fid);
    return [[BabyDao getInstance]getBabies:[self getUserInfo].fid];
}

-(BabyInfo*)getCurrentBaby
{
    NSArray *arr = [self getMyBabies];
    BabyInfo *baby = [[BabyInfo alloc]init];
    if(arr!=nil && arr.count>0){
        NSUInteger count = arr.count;
        for(int i=0;i<count;i++){
            BabyInfo *b = [arr objectAtIndex:i];
            if(b.focusid>0){
                baby = b;
            }
        }
        if(baby.cid==0){
            baby = arr[0];
        }
    }
    return baby;
}

-(BOOL)logOut
{
    user_info.hasLogin =0;
    user_info.userId=0;
    BOOL result = [[DBManager getInstanse]updateTable:table_name updateDict:@{@"hasLogin":@(0)} limits:[NSString stringWithFormat:@" id =%ld ",[self getUserInfo].userId]];
    
    return YES;
}

@end
